# -*- coding: utf-8 -*-
from django.db.models.query_utils import Q
from django.utils.http import urlencode
from mechanize._mechanize import FormNotFoundError
from pyquery import PyQuery
from requests.exceptions import ConnectionError
from export.magento.models import *
from export.models import *
from export.services import transliterate
from settings import _browser, db

class ImportIntoMagento():
    mainUrl = 'http://nadiyno.com.ua/index.php/admin/'
    browser = _browser

    def __init__(self):
        self.login()

    def login(self):
        try:
            self.browser.open(self.mainUrl)
            try:
                self.browser.select_form(nr=0)
                self.browser.form.set_all_readonly(False)
                self.browser['login[username]'] = 'vicammon'
                self.browser['login[password]'] = 'a1111111'
                self.browser.submit()
            except  FormNotFoundError:
                pass
            url = self.browser.geturl()
            url = url.split('/key/')
            self.key = url[1][:len(url[1])-1]
            return True
        except ConnectionError, IndexError:
            return False

    def importProducts(self, products):
        for product in products:
            self.get_or_createProduct(product)

    def setAttr(self, attribute):
        data= {'attribute_code': 'parser_' + attribute.attr_name.replace(' ', '_'), 'is_global': 1,
               'default_value_yesno': 0, 'is_unique': 0, 'is_required': 0, 'is_configurable': 0, 'is_shown_in_short': 0,
               'is_searchable': 0, 'is_visible_in_advanced_search': 0, 'is_comparable': 0, 'is_filterable': 0,
               'is_filterable_in_search': 0, 'is_used_for_promo_rules': 0, 'position': 99, 'is_html_allowed_on_front': 0,
               'is_visible_on_front': 0, 'used_in_product_listing': 0, 'frontend_label[0]': attribute.attr_name}
        lenAttrValues=0
        values = BaseProduct_Attr_Value.objects.filter(attr=attribute)
        for value in values:
            lenAttrValues+=1
            data['text','option[value][option_%s][0]'%lenAttrValues]=value.attr_value
            data['text','option[value][option_%s][1]'%lenAttrValues]=''
            data['text','option[order][option_%s]'%lenAttrValues]=0
        self.browser.open(self.mainUrl+'catalog_product_attribute/save/key/d665dbcf82e30fb34d562308d3aa2a59/back/edit/tab/product_attribute_tabs_labels',urlencode(data))


#        self.browser.click

    def setProduct(self, product, attrSetId=None):
        if not attrSetId:
            attrSetId=self.get_or_createAttrSet(product)
            url=self.mainUrl+'catalog_product/save/back/edit/tab/product_info_tabs_group_8/set/%s/type/simple/key/%s/'%(attrSetId,self.key)
        else:
            url=self.mainUrl+'catalog_product/save/back/edit/tab/product_info_tabs_group_242/id/%s/key/%s/'%(product.entity_id,self.key)
        data= {'form_key': '5cINDq99WrT48UWx', 'product[main_type]': product.group, 'product[owner]': 4121,
               'product[name]': product.name, 'product[description]': product.description,
               'product[short_description]': product.short_description, 'product[sku]': product.sku,
               'product[weight]': 99, 'product[url_key]': transliterate(product.name), 'product[visibility]': 4,
               'product[super_offer]': 0, 'product[msrp_enabled]': 2, 'product[msrp_display_actual_price_type]': 4,
               'product[enable_googlecheckout]': 1, 'product[tax_class_id]': 4, 'product[is_recurring]': 0,
               'product[options_container]': 'container2', 'product[use_config_gift_message_available]': 1,
               'product[stock_data][use_config_manage_stock]': 1, 'product[stock_data][original_inventory_qty]': 0,
               'product[stock_data][qty]': 0, 'product[stock_data][use_config_min_qty]': 1,
               'product[stock_data][use_config_min_sale_qty]': 1, 'product[stock_data][use_config_max_sale_qty]': 1,
               'product[stock_data][is_qty_decimal]': 0, 'product[stock_data][is_decimal_divided]': 0,
               'product[stock_data][use_config_backorders]': 1, 'product[stock_data][use_config_notify_stock_qty]': 1,
               'product[stock_data][use_config_enable_qty_increments]': 1,
               'product[stock_data][use_config_qty_increments]': 1, 'product[stock_data][is_in_stock]': 0,
               'product[brand_name]': product.brand_name}
        avail=BaseProduct_Stock_Availability.objects.filter(product_id=product).filter(~Q(availability='Нет'))
        if avail:
            data['product[status]']=2
        else:
            data['product[status]']=1
        prices=BaseProduct_Price.objects.filter(sku=product)
        data['product[price]']=prices[0]
        self.browser.open(url,data=urlencode(data))
        product.entity_id=FirstcatalogProductEntity.objects.using('magento').get(entity_id=product.entity_id).entity_id
        product.save()

    def setAttrSet(self, product, attributes):
        attrsId=self.get_or_createAttrs(product)
        attrSetId=self.browser.open(self.mainUrl+'catalog_product_set/index/key/%s/?import=set&name=%s&attrs=%s'%(self.key, 'nadiyno '+product.group, str(attrsId)))
        return attrSetId

    def get_or_createAttr(self, attribute):
        try:
            attribute_=FirsteavAttribute.objects.using('magento').get(attribute_code='parser_'+attribute.attr_name.replace(' ','_'))
        except FirsteavAttribute.DoesNotExist:
            self.setAttr(attribute)
            attribute_=FirsteavAttribute.objects.using('magento').get(attribute_code='parser_'+attribute.attr_name.replace(' ','_'))
        self.updateValueAttr(attribute_, BaseProduct_Attr_Value.objects.filter(attr=attribute))
        return FirsteavAttribute.objects.using('magento').get(attribute_code='parser_'+attribute.attr_name.replace(' ','_')).attribute_id

    def get_or_createAttrs(self, product):
        attributesValue = BaseProduct_Attr_Value.objects.filter(sku_id=product)
        attributes=[]
        for attrValue in attributesValue:
            attributes.append(BaseProduct_Attr.objects.get(attr_name=attrValue.attr.attr_name))
        attrsId=[]
        for attribute in attributes:
            attrsId.append(self.get_or_createAttr(attribute))
        return attrsId

    def get_or_createAttrSet(self, product):
        attributes=self.get_or_createAttrs(product)
        _attrSetId = FirsteavAttributeSet.objects.using('magento').get(attribute_set_name = product.group, entity_type_id=4).attribute_set_id
        if not _attrSetId:
            _attrSetId=self.setAttrSet(product, attributes)
        return _attrSetId

    def get_or_createProduct(self, product):
        if not product.entity_id:
            product.entity_id=self.setProduct(product)
        else:
            self.setProduct(product, product.entity_id)

    def changeProductStatus(self):
        pass

    def updateValueAttr(self, attribute_, values):
        jQuery = PyQuery(self.browser.open(self.mainUrl+'catalog_product_attribute/edit/attribute_id/%s/key/%s/'%(attribute_[0],self.key)).get_data())
        currectValues = jQuery('.dynamic-grid input')
        value_=[]
        lenAttrValues=len(currectValues)
        for temp in currectValues:
            value_.append(temp.text_content())
        for value in values:
            if value not in value_:
                lenAttrValues+=1
                self.browser.form.new_control('text','option[value][option_%s][0]'%lenAttrValues,{'value':value})
                self.browser.form.new_control('text','option[value][option_%s][1]'%lenAttrValues,{'value':''})
                self.browser.form.new_control('text','option[order][option_%s]'%lenAttrValues,{'value':0})
        self.browser.form.fixup()
        self.browser.submit()
